﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using SoonCode.Core;
using SoonCode.FocusTest.Api;
using SoonCode.FocusTest.Events;
using SoonCode.FocusTest.Models;
using SoonCode.FocusTest.Utils;
using SoonCode.FocusTest.Views;
using SoonCode.FocusTest.Views.Teacher;
using MessageBox = HandyControl.Controls.MessageBox;

namespace SoonCode.FocusTest.ViewModels
{
    class SelectMemberViewModel : BindableBase
    {
        private IDialogService _dialogService;
        private IEventAggregator aggregator;
        public SelectMemberViewModel(IEventAggregator aggregator, IDialogService dialogService)
        {
            this._dialogService=dialogService;
            this.aggregator=aggregator;
            aggregator.GetEvent<CloseTestEvent>().Subscribe(CloseTest);
            aggregator.GetEvent<PrepareTestEvent>().Subscribe(InitTest);
        }

        private MemberInfo memberInfo=new MemberInfo(){name = "请选择被测试人员"};
        private string teacher="";
        private bool isSelectMember=false;
        private bool isReview=false;
        private int teacherSelect = -1;
        private ObservableCollection<TeacherModel> teacherList;

        public int TeacherSelect
        {
            get => teacherSelect;
            set
            {
                teacherSelect = value;
                RaisePropertyChanged();
            }
        }

        public ObservableCollection<TeacherModel> TeacherList
        {
            get => teacherList;
            set
            {
                teacherList=value;
                RaisePropertyChanged();
            }
        }

        public MemberInfo MemberInfo
        {
            get { return memberInfo; }
            set
            {
                this.memberInfo= value;
                RaisePropertyChanged();
            }
        }

        public string Teacher
        {
            get
            {
                return teacher;
            }
            set
            {
                teacher = value;
                RaisePropertyChanged();
            }
        }

        public bool IsReview {
            get
            {
                return isReview;
            }
            set
            {
                isReview = value;
                RaisePropertyChanged();
            }
        }

        public async void InitTest()
        {
            TeacherList = await API.GetTeacherList(GlobalModel.Instance.OrgInfo.id);
            MemberInfo = new MemberInfo() { name = "请选择被测试人员" };
            Teacher = "";
            
            isSelectMember = false;
            if (!GlobalModel.Instance.Teacher.IsNullOrEmpty())
            {
                Teacher= GlobalModel.Instance.Teacher;
            }
            SoundPlayer.Play("prepare.mp3");
            if (FileHelper.Exists(GlobalModel.AccountDir + "test.data"))
            {
                string testJson = FileHelper.ReadTxt(GlobalModel.AccountDir + "test.data");
                TestInfo test = JsonSerializer.Deserialize<TestInfo>(testJson);
                var result = MessageBox.Show($"您有一个评测尚未完成，姓名：{test.name}，是否继续评测？",
                    "系统提示",MessageBoxButton.YesNo,MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    string memberJson = FileHelper.ReadTxt(GlobalModel.AccountDir + "member.data");
                    MemberInfo member= JsonSerializer.Deserialize<MemberInfo>(memberJson);
                    GlobalModel.Instance.TestInfo = test;
                    GlobalModel.Instance.MemberInfo = member;
                    this.aggregator.GetEvent<StartTestEvent>().Publish();
                }
                else
                {
                    FileHelper.DeleteFile(GlobalModel.AccountDir + "test.data");
                    FileHelper.DeleteFile(GlobalModel.AccountDir + "member.data");
                }
            }
        }

        public ICommand OnSelectTeacher
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    this._dialogService.ShowDialog(nameof(SelectTeacher), (res) =>
                    {
                        if (res.Result == ButtonResult.Yes)
                        {
                            this.Teacher = res.Parameters.GetValue<string>("theater");
                            GlobalModel.Instance.Teacher= this.Teacher;
                        }

                    });
                });
            }
        }
        public ICommand OnSelectMemeber
        {
            get
            {
                return new DelegateCommand(() =>
                {
                     this._dialogService.ShowDialog(nameof(MemberList), (res) =>
                     {
                         if (res.Result == ButtonResult.Yes)
                         {
                             this.MemberInfo = res.Parameters.GetValue<MemberInfo>("member");
                             isSelectMember = true;
                         }

                     });
                });
            }
        }

        public ICommand OnStartTest
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    if (!isSelectMember||Teacher.IsNullOrEmpty())
                    {
                        MessageBox.Show("请选择被测试人，并选择评测老师！", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }

                    OrgInfo orgInfo = GlobalModel.Instance.OrgInfo;
                    if (orgInfo.serviceType == "frequency" && orgInfo.testNumber <= 0)
                    {
                        MessageBox.Show("您的评测次数已经用完！", "系统提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    GlobalModel.Instance.Teacher = this.Teacher;
                    GlobalModel.Instance.MemberInfo = this.MemberInfo;
                    GlobalModel.Instance.MemberInfo.testItem = 0;
                    TestInfo testInfo = new TestInfo();
                    GlobalModel.Instance.TestInfo = testInfo;
                    testInfo.teacher = this.Teacher;
                    testInfo.check_type = this.IsReview ? "1" : "0";
                    testInfo.name = this.memberInfo.name;
                    testInfo.sex=this.memberInfo.sex;
                    testInfo.age = this.memberInfo.showAge;
                    testInfo.memberId = this.memberInfo.id;
                    testInfo.member_no=this.memberInfo.member_no;
                    this.aggregator.GetEvent<StartTestEvent>().Publish();
                });
            }
        }

        public void CloseTest()
        {
            SoundPlayer.Stop();
        }
    }
}
